<template>
  <div class="gas">
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               ref="crud"
               @row-del="rowDel"
               v-model="form"
               :permission="permissionList"
               @row-update="rowUpdate"
               @row-save="rowSave"
               :before-open="beforeOpen"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="success" size="small" plain v-if="permissionList" icon="el-icon-upload2" @click="handleImport">导 入</el-button>
        <el-button type="warning" size="small" plain v-if="permissionList" icon="el-icon-upload1" @click="handleExport">导 出</el-button>
        <el-button type="danger" size="small" plain v-if="permission.gas_delete" @click="handleDelete">删 除</el-button>



      </template>

      <template slot="idsLabel">
        <span style="color:#F56C6C">*</span><span>关联DCS:</span>
      </template>
      <template slot="idsForm">
        <div v-if="dialogType !== 'view'">
        <el-form label-width="0px">
          <el-button
            type="success"
            size="small"
            @click="handleDcs">
            选择 DCS
          </el-button>
          <span v-if="dcsTagsErr" class="dsc_error">请选择DCS数据点</span>
          <div class="dcs_point_list">
            <el-tag
              :key="index"
              v-for="(tag, index) in dcsTags"
              closable
              :disable-transitions="false"
              @close="closeDcsTag(index)">
              {{tag.dwbq}}
            </el-tag>
          </div>
        </el-form>
        </div>
      </template>

      <!-- 地图表单自定义 -->
      <template slot="mapForm">
        <div v-if="showMap">
          <baidu-map class="map" :center="center" :zoom="zoom" @ready="handler">
            <el-input placeholder="关键词查询" v-model="searchWord" style="position:absolute;top:10px;left:10px;width:180px;">
              <template slot="append">
                <el-button icon="el-icon-search" id="citySearch"></el-button>
              </template>
            </el-input>

            <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
            <bm-marker :position="mapPosition" :dragging="true"></bm-marker>
          </baidu-map>
        </div>
      </template>

    </avue-crud>

    <!-- 关联DCS弹窗 -->
    <el-dialog
      title="选择 DCS"
      :visible.sync="dialogDcs"
      append-to-body
      @close='closeDialog'
      width="1200px"
    >
      <avue-crud
        :option="dcsOption"
        :table-loading="dcsLoading"
        :data="dcsData"
        :page.sync="dcsPage"
        ref="dcsCrud"
        @search-change="dcsSearchChange"
        @search-reset="dcsSearchReset"
        @selection-change="dcsSelectionChange"
        @current-change="dcsCurrentChange"
        @size-change="dcsSizeChange"
      >
        <!-- 自定义状态 -->
        <template slot="zt" slot-scope="scope">
          <div v-if="scope.row['zt'] === 1">在线</div>
          <div v-else>下线</div>
        </template>
      </avue-crud>

      <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="chooseDcs()">确 定</el-button>
        </span>
    </el-dialog>

<!--    <el-dialog-->
<!--      title="附件管理"-->
<!--      append-to-body-->
<!--      :visible.sync="excelBox"-->
<!--      width="555px"-->
<!--    >-->
<!--      <avue-form-->
<!--        :option="excelOption"-->
<!--        v-model="excelForm"-->
<!--        :upload-after="uploadAfter"-->
<!--        :upload-before="beforeUpload"-->
<!--        :upload-error="uploadError">-->
<!--      </avue-form>-->
<!--    </el-dialog>-->

    <el-dialog title="数据导入"
               append-to-body
               :visible.sync="excelBox"
               width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :show-file-list="false" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>


  </basic-container>
  </div>
</template>

<script>
import {getList, remove, update, add, getDetail,getDCSList} from "@/api/mmhi/gas";
import {mapGetters} from "vuex";
import {getToken} from "@/util/auth";


export default {
  data() {
    return {
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [{
          label: '表格导入',
          prop: 'excelFile',
          type: 'upload',
          drag: true,
          loadText: '表格导入中，请稍等',
          showFileList: false,
          span: 24,
          propsHttp: {
            fileName: 'file',
            res: 'data'
          },
          tip: '请上传 .xls,.xlsx 标准格式文件',
          action: "/api/gas/import-gas",
          headers: {}
        },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          }
        ]
      },

      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],

      option: {
        height: 'auto',
        calcHeight: 30,
        dialogWidth: 950,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        excelBtn: false,
        dialogClickModal: false,
        dic:"dic",
        column: [
          {
            label: "气体类型",
            prop: "type",
            type:"select",
            align: "center",
            cascaderIndex:0,
            cascaderItem: ['qtlx'],
            dicUrl:"/api/blade-system/dict-biz/dictionary?code=gas_type",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dataType: "number",
            row: false,
            search: true,
            rules: [{
              required: true,
              message: "请选择气体类型",
              trigger: "blur"
            }],

          },
          {
            label: "可燃有毒气体类型",
            prop: "qtlx",
            row: false,
            align: "center",
            type:"select",
            cascaderIndex:0,
            dicUrl:"/api/gas/getQtlxList?code={{key}}",
            props: {
              label: "dictValue",
              value: "dictValue"
            },
            rules: [{
              required: true,
              message: "请选择可燃有毒气体类型",
              trigger: "blur"
            }],
            hide:true,
          },
          {
            label: "传感器编号",
            prop: "qtcgqbh",
            align: "center",
            width:"100px",
            row: false,
            rules: [{
              required: true,
              message: "传感器编号",
              trigger: "blur"
            }]
          },
          {
            label: "传感器位置",
            prop: "qtcgqwz",
            align: "center",
            width:"100px",
            row: false,
            rules: [{
              required: true,
              message: "传感器位置",
              trigger: "blur"
            }]
          },
          {
            label: '',
            prop: 'map',
            span: 24,
            hide: true,
            formslot: true,
          },
          {
            label: "经度",
            prop: "jd",
            row: false,
            hide: true,
            rules: [{
              required: true,
              message: "经度",
              trigger: "blur"
            }]
          },
          {
            label: "纬度",
            prop: "wd",
            row: false,
            hide: true,
            rules: [{
              required: true,
              message: "纬度",
              trigger: "blur"
            }]
          },
          {
            label: "气体浓度第一级报警阈值(mg/m³)",
            prop: "qtbjyz1",
            row: false,
            align: "center",
            width:"230px",
            rules: [{
              required: true,
              message: "气体浓度第一级报警阈值",
              trigger: "blur"
            }]
          },{
            label: "气体浓度第二级报警阈值(mg/m³)",
            prop: "qtbjyz2",
            row: false,
            align: "center",
            width:"230px",
            rules: [{
              required: true,
              message: "气体浓度第二级报警阈值",
              trigger: "blur"
            }]
          },{
            label: "气体报警浓度",
            prop: "qtbjnd",
            row: false,
            align: "center",
            width:"150px",
            rules: [{
              required: true,
              message: "气体报警浓度",
              trigger: "blur"
            }]
          },{
            label: "气体报警时间",
            prop: "qtbjsj",
            row: false,
            align: "center",
            width:"150px",
            type: "datetime",
            format: "yyyy-MM-dd hh:mm:ss",
            valueFormat: "yyyy-MM-dd hh:mm:ss",            //search: true,
            rules: [{
              required: true,
              message: "气体报警时间",
              trigger: "blur"
            }]
          },{
            label: "气体实时浓度(mg/m³)",
            prop: "qtssnd",
            row: false,
            align: "center",
            width:"180px",
            rules: [{
              required: true,
              message: "气体实时浓度",
              trigger: "blur"
            }]
          },
          {
            label: "DCS点",
            prop: "dwbq",
            align: "center",
            hide: true,
            addDisplay: false,
            viewDisplay: false,
            editDisplay: false
          },
          {
            label: "关联DCS",
            prop: "ids",
            align: "center",
            hide: true,
            viewDisplay: false,
            formslot:true,
            labelslot:true,
          },
          {
            label: "企业id",
            prop: "bladeDeptId",
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          },
          {
            label: "租户id",
            prop: "tenantId",
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          },
          {
            label: "创建人",
            prop: "createUser",
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          },
          {
            label: "创建部门",
            prop: "createDept",
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          },
          {
            label: "创建时间",
            prop: "createTime",
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          }
        ]
      },
      data: [],
      mapPosition: {
        lng: 121.4472540000,
        lat: 31.3236200000
      },
      center: {
        lng: 121.4472540000,
        lat: 31.3236200000
      },
      zoom: 10,
      dragging: false,
      showMap: true,
      searchWord: "",
      dialogDcs: false,
      dialogType:'',
      dcsQuery: {},
      dcsLoading: true,
      dcsPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      dcsSelectionList: [],
      dcsOption: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        menu: false,
        addBtn: false,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        refreshBtn: false,
        columnBtn: false,
        column: [
          {
            label: "点位标签",
            prop: "dwbq",
            align: "center",
            search: true,
            rules: [{
              required: true,
              message: "请输入点位标签",
              trigger: "blur"
            }]
          },
          {
            label: "点位名称",
            prop: "dwmc",
            align: "center",
            search: true,
            rules: [{
              required: true,
              message: "请输入点位名称",
              trigger: "blur"
            }]
          },
          {
            label: "点位类型",
            prop: "dwlx",
            align: "center",
            type: 'select',
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=dcs_data_site_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [{
              required: true,
              message: "请选择点位类型",
              trigger: "blur"
            }]
          },
          {
            label: "最大值",
            prop: "zdfz",
            align: "center",
            type: "number",
            rules: [{
              required: true,
              message: "请输入最大值",
              trigger: "blur"
            }]
          },
          {
            label: "最小值",
            prop: "zxfz",
            align: "center",
            type: "number",
            rules: [{
              required: true,
              message: "请输入最小值",
              trigger: "blur"
            }]
          },
          {
            label: "单位",
            prop: "dw",
            align: "center",
            rules: [{
              required: true,
              message: "请输入单位",
              trigger: "blur"
            }]
          },
          {
            label: "状态",
            prop: "zt",
            align: "center",
            slot: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          }
        ]
      },
      dcsData: [],
      dcsTags: [],
      dcsTagsErr: false,
      selectDcs: {},

    };
  },

  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.gas_add, false),
        viewBtn: this.vaildData(this.permission.gas_view, false),
        delBtn: this.vaildData(this.permission.gas_delete, false),
        editBtn: this.vaildData(this.permission.gas_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  watch: {
    // 'excelForm.isCovered'() {
    //   if (this.excelForm.isCovered !== '') {
    //     const column = this.findObject(this.excelOption.column, "excelFile");
    //     column.action = `/api/gas/import-gas=${this.excelForm.isCovered}`;
    //   }
    // },
    // 表单经度
    'form.jd' (val) {
      if(val) {
        this.mapPosition.lng = val / 1
      }
    },

    // 表单纬度
    'form.wd' (val) {
      if(val) {
        this.mapPosition.lat = val / 1
      }
    }
  },
  methods: {
    // 地图处理事件
    handler({BMap, map}) {
      let _this = this;
      map.addEventListener('click', function(e) {
        _this.form.jd = e.point.lng
        _this.form.wd = e.point.lat
      });

      _this.$nextTick(() => {
        document.getElementById('citySearch').addEventListener('click', function() {
          let localSearch = new BMap.LocalSearch(map)
          localSearch.setSearchCompleteCallback(searchResult => {
            let poi = searchResult.getPoi(0)
            if(!poi) {
              return _this.$message.warning('该地址不存在')
            } else {
              _this.center = {
                lng: poi.point.lng,
                lat: poi.point.lat
              }
              _this.form.jd = poi.point.lng
              _this.form.wd = poi.point.lat
            }
          });
          localSearch.search(_this.searchWord);
        });
      })
    },

    // 弹出导入框
    handleImport() {
      this.excelBox = true;
    },

    // 导入前判断
    beforeUpload(file, done, loading) {
      this.isFailed = false;
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xls'
      const extension2 = testmsg === 'xlsx'
      if(!extension && !extension2) {
        this.$message.warning('请上传 .xls,.xlsx 标准格式文件!');
        loading()
      } else {
        done()
      }
    },

    // 导入失败后
    uploadError(error, column) {
      console.log(error,column);
      this.isFailed = true;
    },

    // 导入成功后
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      this.excelBox = false;
      this.refreshChange();
      done();
    },

    // 取消
    cancle() {
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },



    //关联dcs功能
    // 打开选择DCS弹窗
    handleDcs() {
      this.dialogDcs = true;
      this.dcsOnLoad(this.dcsPage);
    },

    // 关闭选择DCS弹窗
    closeDialog() {
      this.dcsPage.currentPage = 1;
      this.dialogDcs = false;
      this.dcsSelectionClear();
    },

    // DCS获取表格数据
    dcsOnLoad(page, params = {}) {
      this.dcsLoading = true;
      getDCSList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.dcsPage.total = data.total;
        this.dcsData = data.records;
        this.dcsLoading = false;
        if(this.selectDcs !== undefined && JSON.stringify(this.selectDcs) !== "{}"  &&  this.dcsTags.length !== 0) {
          this.$nextTick(() => {
            this.dcsData.forEach(row => {
              if(this.selectDcs[row.id] !== undefined) {
                this.$refs.dcsCrud.toggleRowSelection(row, true);
              }
            })
          })
        }
      });
    },

    // DCS清空勾选
    dcsSelectionClear() {
      this.dcsSelectionList = [];
      this.$refs.dcsCrud.toggleSelection();
    },

    // DCS搜索条件改变事件
    dcsSearchChange(params, done) {
      this.dcsQuery = params;
      this.dcsPage.currentPage = 1;
      this.dcsOnLoad(this.dcsPage, params);
      done();
    },

    // DCS清空搜索条件
    dcsSearchReset() {
      this.dcsQuery = {};
      this.dcsOnLoad(this.dcsPage);
    },

    // DCS勾选
    dcsSelectionChange(list) {
      this.dcsSelectionList = list;
    },

    // DCS换页数
    dcsCurrentChange(currentPage){
      var pageSelectIds = [];
      var pageAllIds = [];
      this.dcsSelectionList.forEach(item => {
        this.selectDcs[item.id] = item;
        pageSelectIds.push(item.id);
      });
      this.dcsData.forEach(item => {
        pageAllIds.push(item.id);
      });
      for(var id in this.selectDcs) {
        if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
          delete this.selectDcs[id];
        }
      }
      this.dcsPage.currentPage = currentPage;
      this.dcsOnLoad(this.dcsPage);
    },

    // DCS换每页显示数量
    dcsSizeChange(pageSize){
      this.dcsPage.pageSize = pageSize;
      this.dcsOnLoad(this.dcsPage);
    },

    // 选择DCS
    chooseDcs() {
      var pageSelectIds = [];
      var pageAllIds = [];
      this.dcsSelectionList.forEach(item => {
        this.selectDcs[item.id] = item;
        pageSelectIds.push(item.id);
      });
      this.dcsData.forEach(item => {
        pageAllIds.push(item.id);
      });
      for(let id in this.selectDcs) {
        if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
          delete this.selectDcs[id];
        }
      }
      if(this.selectDcs === undefined || JSON.stringify(this.selectDcs) === "{}") {
        this.$message.warning("请选择DCS数据点");
        return;
      }
      this.dcsTagsErr = false;
      this.dcsTags = [];
      for(let id in this.selectDcs) {
        this.dcsTags.push(this.selectDcs[id]);
      }
      this.closeDialog();
    },

    // 删除某一个dcs标签
    closeDcsTag(index) {
      this.dcsTags.splice(index, 1);
      if(this.dcsTags.length === 0) {
        this.dcsTagsErr = true;
      }
    },


    rowSave(row, done, loading) {
      if(this.dcsTags.length === 0) {
        this.dcsTagsErr = true;
        loading();
        return;
      }
      delete row.dwbq;
      var idsArr = [];
      this.dcsTags.forEach(item => {
        idsArr.push(item.id);
      });
      row.ids = idsArr.join(",");
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done,loading) {
      if(this.dcsTags.length === 0) {
        this.dcsTagsErr = true;
        loading();
        return;
      }
      var idsArr = [];
      var updateData = {
        id: row.id,
        qtlx: row.qtlx,
        qtcgqbh: row.qtcgqbh,
        qtcgqwz: row.qtcgqwz,
        qtbjyz1: row.qtbjyz1,
        qtbjyz2: row.qtbjyz2,
        qtbjnd: row.qtbjnd,
        qtbjsj: row.qtbjsj,
        qtssnd: row.qtssnd,
        type:row.type,
        jd: row.jd,
        wd: row.wd,
        dwbq: row.dwbq,
        dwmc: row.dwmc,
        zdfz: row.zdfz,
        zxfz: row.zxfz,
        dwlx: row.dwlx,
        dw: row.dw,
        zt: row.zt,
        bladeDeptId: row.bladeDeptId,
        tenantId: row.tenantId,
        createUser: row.createUser,
        createDept: row.createDept,
        createTime: row.createTime,
        ids: "",
      };
      this.dcsTags.forEach(item => {
        idsArr.push(item.id);
      });
      updateData.ids = idsArr.join(",");
      update(updateData).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      this.dcsTagsErr = false;
      this.dcsTags = [];
      this.selectDcs = {};
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          this.form.dcsDataSiteInfos.forEach(item => {
            this.dcsTags.push(item);
            this.selectDcs[item.id] = item;
          });
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      const {releaseTimeRange} = params;
      let values = {
        ...params,
      };
      if (releaseTimeRange) {
        values = {
          ...params,
          releaseTime_datege: releaseTimeRange[0],
          releaseTime_datelt: releaseTimeRange[1],
        };
        values.releaseTimeRange = null;
        this.query.releaseTimeRange = null;
      }
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(values, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleTemplate() {
      window.open(`/api/gas/export-template?${this.website.tokenHeader}=${getToken()}`);
    },
    handleExport() {
      this.$confirm("是否导出可燃有毒气体信息?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        window.open(`/api/gas/export-gas?${this.website.tokenHeader}=${getToken()}`);
      });
    },
  }
};
</script>

<style>
.map {
  width: 100%;
  height: 500px;
}
.dsc_error {
  color: red;
}
</style>
<style lang="scss" scpoed>
  .avue-crud__dialog {
    .el-dialog__body {
      .el-form-item__label {
        width: 180px !important;
      }

      .avue-form__row {
        .el-form-item__content {
          margin-left: 180px !important;
        }
      }
    }
  }
</style>
